package com.trace.demo.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 日期处理配置
 * 处理无效的日期格式
 */
@Configuration
public class DateConfig {

    /**
     * 自定义LocalDateTime反序列化器
     * 处理无效的日期格式，返回当前时间
     */
    public static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
            String dateString = jsonParser.getText();
            
            // 特殊处理 - 如果输入包含占位符如yyyy-MM-dd，则直接返回当前时间
            if (dateString.contains("yyyy") || dateString.contains("MM") || dateString.contains("dd")) {
                System.out.println("日期包含格式化占位符: " + dateString + "，使用当前时间代替");
                return LocalDateTime.now();
            }
            
            // 尝试不同格式解析
            DateTimeFormatter[] formatters = {
                DateTimeFormatter.ISO_LOCAL_DATE_TIME,  // 标准ISO格式
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
                DateTimeFormatter.ofPattern("yyyy-MM-dd"),
                DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
                DateTimeFormatter.ofPattern("yyyy/MM/dd")
            };
            
            for (DateTimeFormatter formatter : formatters) {
                try {
                    // 尝试用当前格式解析
                    if (dateString.length() <= 10) {
                        // 如果只有日期部分，添加时间部分
                        return LocalDateTime.parse(dateString + " 00:00:00", 
                                  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    }
                    return LocalDateTime.parse(dateString, formatter);
                } catch (DateTimeParseException e) {
                    // 此格式解析失败，继续尝试下一个
                    continue;
                }
            }
            
            // 所有解析都失败，返回当前时间
            System.out.println("无法解析日期: " + dateString + "，使用当前时间代替");
            return LocalDateTime.now();
        }
    }

    /**
     * 配置消息转换器
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
        
        // 注册Java 8日期模块
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        
        // 创建并注册自定义的LocalDateTime反序列化器
        SimpleModule customModule = new SimpleModule();
        customModule.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
        
        objectMapper.registerModules(javaTimeModule, customModule);
        converter.setObjectMapper(objectMapper);
        
        return converter;
    }
} 